//
//  Tools.m
//  blocklover
//
//  Created by 冯业宁 on 2018/7/11.
//  Copyright © 2018年 Allen.feng. All rights reserved.
//

#import "Tools.h"

@implementation Tools

#pragma mark 获取时间差根据开始时间戳
+(NSString*)getTimeDiffWithStartTime:(long)StartTime {
    NSString *time;
    int timeDiff = [[NSDate date] timeIntervalSince1970] - StartTime;
    if (timeDiff < 60) {
        time = @"刚刚";
    }else if(timeDiff < 3600) {
        time = [NSString stringWithFormat:@"%d分钟前", timeDiff/60];
    }else if(timeDiff < 86400) {
        time = [NSString stringWithFormat:@"%d小时前", timeDiff/3600];
    }else {
        if (timeDiff/86400 > 7) {
            time = [NSString stringWithFormat:@"7天前"];
        }else{
            time = [NSString stringWithFormat:@"%d天前", timeDiff/86400];
        }
    }
    return time;
}

#pragma mark 获取设备尺寸
+(CGSize)getDiviceSize{
    CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    return size;
}

#pragma mark 获取动态行高
+(float)getDynamicHeightWithWidth:(float)width fontSize:(float)fontSize Text:(NSString *)text numOfLins:(int)num spacing:(int)spacing {
    UILabel *label = [[UILabel alloc]init];
    [label setText:text];
    [label setFont:[UIFont systemFontOfSize:fontSize]];
    [label setNumberOfLines:num];
    if (spacing > 0) {
        NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:label.text];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:spacing];
        [attributedStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])];
        label.attributedText = attributedStr;
    }
    CGRect rectTitle = [label textRectForBounds:CGRectMake(0, 0, width, 999) limitedToNumberOfLines:num];
    return rectTitle.size.height;
}

#pragma mark 获取富文本动态行高
+(CGFloat)getSpaceLabelHeight:(NSString *)str withAttrDict:(NSMutableDictionary *)dict withWidth:(CGFloat)width linesNum:(int)linesNum {
    CGSize size = [str boundingRectWithSize:CGSizeMake(width, linesNum) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    return size.height;
}

#pragma mark 获取label的size
+(CGSize)getDynamicSizeWithText:(NSString *)text font:(UIFont *)font{
    UILabel *label = [[UILabel alloc]init];
    label.text = text;
    return [label.text sizeWithAttributes:@{NSFontAttributeName: font}];
}

#pragma mark 获取导航栏高度
+(float)getStatusBarHeight {
    return UIApplication.sharedApplication.statusBarFrame.size.height;
}

#pragma mark 设置苹方字体
+(NSString*)setFontNamePingFang{
    return @"PingFangSC-Medium";
}

+(NSString*)setFontNamePingFangBold{
    return @"PingFangSC-Semibold";
}

+(NSString*)setFontNamePingFangRegular{
    return @"PingFangSC-Regular";
}



#pragma mark 获取当前时间戳
+(NSString *)getDateTime{
    UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
    NSString *timeString = [NSString stringWithFormat:@"%llu", recordTime];
    return timeString;
}

#pragma mark 16进制颜色转UIColor
+(UIColor *) hexStringToUIColor: (NSString *) hexString{
    NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    if ([cString length] < 6) return [UIColor blackColor];
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    unsigned int r, g, b;
    
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

#pragma mark 提示信息弹出自动消失
+(void)showMessage:(NSString *)message{
    if ([message isEqualToString:@""] || message==nil) {
        return;
    }
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    UIView *showview;
    if([window viewWithTag:4005]!=nil){
        showview = [window viewWithTag:4005];
    }else{
        showview =  [[UIView alloc]init];
        showview.tag = 4005;
        showview.backgroundColor = [UIColor blackColor];
        showview.frame = CGRectMake(1, 1, 1, 1);
        showview.alpha = 1.0f;
        showview.layer.cornerRadius = 5.0f;
        showview.layer.masksToBounds = YES;
        [window addSubview:showview];
    }
    
    UILabel *label = [[UILabel alloc]init];
    label.text = message;
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentLeft;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:20];
    NSDictionary *attribute = @{NSFontAttributeName: label.font};
    CGSize LabelSize = [message boundingRectWithSize:CGSizeMake([self getDiviceSize].width-30, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine attributes:attribute context:nil].size;
//    CGSize LabelSize = [message sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake([self getDiviceSize].width-30,MAXFLOAT)lineBreakMode:NSLineBreakByWordWrapping];
    label.frame = CGRectMake(5, 5, LabelSize.width+5, LabelSize.height);
    [label setNumberOfLines:0];
    [showview addSubview:label];
    showview.frame = CGRectMake(([self getDiviceSize].width-LabelSize.width-10)/2, ([self getDiviceSize].height - LabelSize.height)/2, LabelSize.width+10, LabelSize.height+10);
    [UIView animateWithDuration:2.0 animations:^{
        showview.alpha = 0;
    } completion:^(BOOL finished) {
        [showview removeFromSuperview];
    }];
}

#pragma mark 获取当前屏幕中present出来的viewcontroller
+(UIViewController *)getPresentedViewController{
    UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *topVC = appRootVC;
    if (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return topVC;
}

#pragma mark 屏幕适配
+(float)theSize:(NSString*)sizeName {
    float with = 375.00;
    float heigh = 667.00;
    float withDiff,heighDiff;

    float screanWidth = [UIScreen mainScreen].bounds.size.width;
    float screanHeight = [UIScreen mainScreen].bounds.size.height;
    
    withDiff = screanWidth/with;
    heighDiff = screanHeight/heigh;
    
    if ([sizeName isEqualToString:@"width"]) {
        return withDiff;
    }else if([sizeName isEqualToString:@"height"]){
        return heighDiff;
    }else{
        NSLog(@"Tools theSize 错误！");
        return 0;
    }
}

#pragma mark 获取ip地址
+(NSDictionary *)deviceWANIPAdress{
    NSError *error;
    NSURL *ipURL = [NSURL URLWithString:@"http://pv.sohu.com/cityjson?ie=utf-8"];
    NSMutableString *ip = [NSMutableString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
    if ([ip hasPrefix:@"var returnCitySN = "]) {
        NSRange range = NSMakeRange(0, 19);
        [ip deleteCharactersInRange:range];
        NSString * nowIp =[ip substringToIndex:ip.length-1];
        NSData * data = [nowIp dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        return dict;
    }
    return nil;
}

#pragma mark 生成清晰二维码
+(UIImage *)creatNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1. 创建bitmap
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

//字典判空字段
+ (NSString *)judgeNullDict:(NSDictionary *)dict string:(NSString *)string
{
    id object = [dict objectForKey:string];
    if ([object isKindOfClass:[NSNull class]]){
        object = @"";
        return object;
    }else{
        return object;
    }
}
//判断版本更新
+ (void)versionTip:(UIViewController *)vc
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    SDUpdate *updater = [SDUpdate shareInstance];
    updater.appleID = @"1437240560";
    updater.curAppVersion = app_Version;
    updater.controller = vc;
    [updater begin];
}
//时间戳转字符串
+ (NSString *)formateDate:(NSString *)string
{
    NSTimeInterval second = string.longLongValue; //毫秒需要除
    
    // 时间戳 -> NSDate *
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:second];
    //    NSLog(@"%@", date);
    
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd HH:mm";
    
    NSString *stringNew = [fmt stringFromDate:date];
    return stringNew;
}

//获取当前时间戳
+ (NSString *)currentTimeStr
{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time = [date timeIntervalSince1970];// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *str = [NSString stringWithFormat:@"%.0f",time];
    return str;
}

//手机号加密
+ (NSString *)secretPhoneNumber:(NSString *)str
{
    NSRange range1;
    range1.location = 0;
    range1.length = 3;
    NSString *str1 = [str substringWithRange:range1];
    
    NSRange range2;
    range2.location = 7;
    range2.length = 4;
    NSString *str2 = [str substringWithRange:range2];
    
    NSString *str3 = @"****";
    NSString *string = [[str1 stringByAppendingString:str3] stringByAppendingString:str2];
    
    return string;
}

// 判断用户是否允许接收通知
+ (BOOL)isUserNotificationEnable {
    BOOL isEnable = NO;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0f) { // iOS版本 >=8.0 处理逻辑
        UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
        isEnable = (UIUserNotificationTypeNone == setting.types) ? NO : YES;
    } else { // iOS版本 <8.0 处理逻辑
        UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        isEnable = (UIRemoteNotificationTypeNone == type) ? NO : YES;
    }
    return isEnable;
}

// 如果用户关闭了接收通知功能，该方法可以跳转到APP设置页面进行修改  iOS版本 >=8.0 处理逻辑
+ (void)goToAppSystemSetting {
    UIApplication *application = [UIApplication sharedApplication];
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([application canOpenURL:url]) {
        if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
            [application openURL:url options:@{} completionHandler:nil];
        } else {
            [application openURL:url];
        }
    }
}

//自适应宽度
/*
 p1:文本
 p2:label对象，目的是调用属性使字体适应宽度
 p3:字体大小
 */
+ (CGSize)getFitWidthText:(NSString *)text label:(UILabel *)label fontSize:(CGFloat)fontSize
{
    label.adjustsFontSizeToFitWidth = YES;
    NSDictionary *attr = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:fontSize]};
    CGSize size = [text sizeWithAttributes:attr];
    return size;
}
//自适应高度
/*
 p1:label文本
 p2:固定宽度
 p3:字体大小
 */
+ (CGSize)getFitHeightText:(NSString *)text labelWidth:(CGFloat)labelWidth fontSize:(CGFloat)fontSize
{
    NSDictionary *attr = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
    CGSize fitHeightSize = CGSizeMake(labelWidth, MAXFLOAT);
    CGSize size = [text boundingRectWithSize:fitHeightSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
    return size;
}

+ (NSString *)setSTSongti_Sc_Bold
{
    return @"STSongti-Sc-Bold";
}



//可变属性字符串
+ (NSMutableAttributedString *)backStr:(NSDictionary *)dict1 str2:(NSDictionary *)dict2
{
    NSMutableAttributedString *attributedString1 = [[NSMutableAttributedString alloc] initWithString:dict1[@"str"]];
    //NSDictionary *dict1 = @{NSForegroundColorAttributeName:BlackColor,NSFontAttributeName:[UIFont systemFontOfSize:14*AdaptRatio]};
    [attributedString1 setAttributes:dict1 range:NSMakeRange(0, attributedString1.length)];
    NSMutableAttributedString *attributedString2 = [[NSMutableAttributedString alloc] initWithString:dict2[@"str"]];
    //NSDictionary *dict2 = @{NSForegroundColorAttributeName:UIColorFromRGB(0xff5e44),NSFontAttributeName:[UIFont systemFontOfSize:14*AdaptRatio]};
    [attributedString2 setAttributes:dict2 range:NSMakeRange(0, attributedString2.length)];
    [attributedString1 appendAttributedString:attributedString2];
    
    return attributedString1;
}

//字符串截取
+ (NSString *)separateString:(NSString *)string length:(NSInteger)length location:(NSInteger)location
{
    NSRange range;
    range.length = length;
    range.location = location;
    string = [string substringWithRange:range];
    return string;
}


@end







